package com.baseframe.secure.aspect;


import com.baseframe.secure.annotation.Power;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.tool.utils.data.ClassUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;
import java.util.List;


/**
 * 处理权限
 */
@Aspect
@Order(Integer.MIN_VALUE)
public class AuthorizeTokenAspect {
    @Around("@annotation(com.baseframe.secure.annotation.Power) || @within(com.baseframe.secure.annotation.Power)")
    public Object authorizeHandle(ProceedingJoinPoint point) throws Throwable {

        //获取当前用户拥有的权限
        List<String> authorities = AuthUtil.getAuthorities();

        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        Power power = ClassUtil.getAnnotation(method, Power.class);

        String[] authorizes = power.authorizes();

        boolean flag = false;

        for (String authorize : authorizes) {
            for (String authority : authorities) {
                if (authority.equals(authorize)){
                    flag =true;
                    break;
                }
            }
        }

        if (!flag){

            String collect = String.join(",", authorizes);

            throw new SecurityException("当前请求需要以下权限:["+collect+"]");
        }


        return point.proceed();
    }

}
